#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#include <cstring>
#include<unistd.h>

int main(){
    int socketfd=socket(AF_UNIX,SOCK_STREAM,0);
    if(socketfd==-1){
        std::cout<<"Error in creating socket"<<std::endl;
        return -1;
    }
    struct sockaddr_un addr;
    memset(&addr,0,sizeof(addr));
    addr.sun_family=AF_UNIX;
    strncpy(addr.sun_path,"./test.sock",sizeof(addr.sun_path)-1);

    if(bind(socketfd,(struct sockaddr*)&addr,sizeof(addr))==-1){
        std::cout<<"绑定失败"<<std::endl;
        perror("bind failed");
        close(socketfd);
        return -1;
    }
    if (listen(socketfd, 5) == -1) {
        perror("listen failed");
        close(socketfd);
        return -1;
    }
    struct sockaddr_un client_addr;
    socklen_t clientlenth=sizeof(client_addr);
    char* messages=new char[1024];
    int clientfd=accept(socketfd,(struct sockaddr*)&client_addr,&clientlenth);
    if(clientfd==-1){
        std::cout<<"Error in accepting client"<<std::endl;
        return -1;
    }
    std::cout<<"Client 连接成功"<<std::endl;
    while(1){
        memset(messages,0,1024);
        ssize_t n=read(clientfd,messages,1024);
        if(n==-1){
            std::cout<<"读取错误"<<std::endl;
            return -1;
        }
        else if(n==0){
            std::cout<<"Client 关闭连接"<<std::endl;
            break;
        }
        else{
            std::cout<<"接收到消息: "<<messages<<std::endl;
            std::string str(messages);
            std::cout<<"发送消息: "<<str.substr(0,n)<<std::endl;
            send(clientfd,messages,n,0);
        }
        sleep(2);
    }
    close(clientfd);
    close(socketfd);
    unlink(addr.sun_path);
    return 0;
}